﻿#include <QThread>
#include "test2.h"

Test2::Test2(QObject *parent) : QObject(parent)
{

}

void Test2::initCommunication(QString com)
{
    m_serialPort=new QSerialPort();
    m_serialPort->setPortName(com);
    m_serialPort->setBaudRate(9600);
    m_serialPort->setDataBits(QSerialPort::Data5);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);  //无流控制
    m_serialPort->setReadBufferSize(1000);
    m_wrap=new SerialPortWrap(m_serialPort);
}

void Test2::moveOneStep(int posA, int posB)
{
    moveToPos(POSTYPE::POSA,posA);
    while(true)
    {
        QThread::msleep(100);
        if(isInPos(POSTYPE::POSA,posA))
        {
            break;
        }
    }

    moveToPos(POSTYPE::POSB,posB);
    while(true)
    {
        QThread::msleep(100);
        if(isInPos(POSTYPE::POSB,posB))
        {
            break;
        }
    }
    qDebug()<<__FUNCTION__<<__LINE__<<posA<<"  "<<posB<<"move ok!";
}

bool Test2::moveToPos(POSTYPE posType,int pos)
{
    //可以理解为每移动到一个位置并且确定到位后再进行下一步动作
    //协议里面没给AB的区分
    QString hexString=QString("5A A5 06 83 10 03 01 00 %1 9E").arg(pos, 2, 16, QChar('0'));
    QByteArray arr = QByteArray::fromHex(hexString.toLatin1());
    m_wrap->requestNoReply(arr);
    return true;
}

bool Test2::isInPos(POSTYPE posType,int pos)
{
    QByteArray arr = QByteArray::fromHex("5A A5 06 84 10 03 01 00 00 9E");
    QByteArray rec;
    m_wrap->request(arr,rec);
    int posA=rec.at(6);
    int posB=rec.at(7);
    if(posType==POSTYPE::POSA)
    {
        return posA==pos;
    }
    else
    {
        return posB==pos;
    }
}
